/**
 * 订阅发布模式，同一个事件存在多个监听
 */
/* eslint-disable no-console */
class EventEmitter {
  constructor() {
    this.listeners = {};
  }

  /**
   * 添加监听
   * @param type 监听标识
   * @param cb 监听触发时候的回调，回调的返回值如果为true时，回调消费后会被销毁
   * @returns {function(...[*]=)}
   */
  on(type, cb) {
    let cbs = this.listeners[type];
    if (!cbs) {
      cbs = [];
    }
    cbs.push(cb);
    this.listeners[type] = cbs;
    return () => {
      this.remove(type, cb);
    };
  }

  /**
   * 触发type类型的监听
   * @param type
   * @param args
   */
  emit(type, ...args) {
    const cbs = this.listeners[type];
    if (Array.isArray(cbs)) {
      for (let i = 0; i < cbs.length; i++) {
        setTimeout(() => {
          const cb = cbs[i];
          if (typeof cb === 'function') {
            const delValue = cb(...args);
            if (delValue) {
              this.remove(type, cb);
            }
          }
        }, i);
      }
    } else {
      console.log(
        `%c event ${type} not exist`,
        'color:rgb(20,150,250);font-size:14px',
      );
    }
  }

  isExist(type) {
    const cbs = this.listeners[type];
    if (cbs) {
      return true;
    }

    return false;
  }

  /**
   * 删除type这个标识下的某个回调
   * @param type
   * @param cb
   */
  remove(type, cb) {
    if (cb) {
      let cbs = this.listeners[type];
      if (cbs) {
        cbs = cbs.filter(ecb => ecb !== cb);
        this.listeners[type] = cbs;
        if (this.listeners[type].length === 0) {
          this.listeners[type] = null;
          delete this.listeners[type];
        }
      }
    } else {
      this.listeners[type] = null;
      delete this.listeners[type];
    }
  }
}
const eventEmitter = new EventEmitter();
window.eventEmitter = eventEmitter;
export default eventEmitter;
